package com.jieshuibao.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.jieshuibao.common.config.Const;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.common.utils.Md5Util;
import com.jieshuibao.mapper.IosWithinMapper;
import com.jieshuibao.mapper.PurchaseOrderMapper;
import com.jieshuibao.model.db.IosWithin;
import com.jieshuibao.model.db.IosWithinExample;
import com.jieshuibao.model.db.PurchaseOrder;
import com.jieshuibao.model.db.User;
import com.jieshuibao.util.IdGen;
import com.jieshuibao.util.JsonUtil;
import com.jieshuibao.util.PayTypeUtil;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.wx.util.PayCommonUtil;

@Service
public class IosWithinService{
	private static final Logger logger = LoggerFactory
			.getLogger("IosWithinService.class");
	@Resource
	private IosWithinMapper iosWithinMapper;
	
	@Resource
	private PurchaseOrderMapper purchaseOrderMapper;
	
	@Resource
	private HttpClientService httpClientService;
	
	@Resource
	private UserDealRecordService userDealRecordService;
	
	@Resource
	private UserService userService;
	
	//购买凭证验证地址
	private static final String certificateUrl = "https://buy.itunes.apple.com/verifyReceipt";
			
				
	//测试的购买凭证验证地址 
				
	private static final String certificateUrlTest = "https://sandbox.itunes.apple.com/verifyReceipt";
	
	public void addIosWithin(IosWithin iosWithin) {
		iosWithinMapper.insertSelective(iosWithin);
	}
	
	public void delIosWithinByUuid(String uuid) {
		iosWithinMapper.deleteByPrimaryKey(uuid);
	}
	
	public void updateIosWithin(IosWithin iosWithin) {
		iosWithinMapper.updateByPrimaryKeySelective(iosWithin);
	}
	
	public IosWithin getIosWithinByUuid(String uuid) {
		return iosWithinMapper.selectByPrimaryKey(uuid);
	}
	
	public List<IosWithin> getPageIosWithin(IosWithinExample iosWithinExample) {
		return iosWithinMapper.selectPage(iosWithinExample);
	}
	
	public int countIosWithin(IosWithinExample iosWithinExample) {
		return iosWithinMapper.countByExample(iosWithinExample);
	}
public boolean isWithInIos(String md5){
		
		if (StringUtils.isNotBlank(md5)) {
			IosWithin bsbWithinIos = iosWithinMapper.selectByPrimaryKey(md5);
			if (bsbWithinIos==null) {
				return false;
			
			}else {
				return true;
			}
			
		}else {
			return false;
		}
		
	}
	
	
	
	
	public Object checkIosResult(String receipt_r,String userId,double price,String receiptMD5){
		BaseRes<String> res = new BaseRes<String>();
		try {
			JSONObject str2Obj = JsonUtil.str2Obj(receipt_r);
				
				JSONArray jsonArray = str2Obj.getJSONArray("in_app");
				JSONObject jsonObject = jsonArray.getJSONObject(0);
				
				int quantity = jsonObject.getInt("quantity");
				
				String product_id = jsonObject.getString("product_id");
				String transaction_id = jsonObject.getString("transaction_id");
				
				long purchase_date_ms = jsonObject.getLong("purchase_date_ms");
				Date date = new Date(purchase_date_ms);
				
				Double money;
				try {
					int indexOf = product_id.indexOf("_");
					int length = product_id.length();
					String substring = product_id.substring(indexOf+1, length);
					money = Double.valueOf(substring);
					
					if (price!=money) {
						//金额不对
						res.setCode(BaseRes.ERRORPARAM_CODE);
						res.setDes("金额不对");
						logger.warn("ios内购二次验证：请求金额与iso验证返回金额不一致！");
						return res;
					}
				} catch (NumberFormatException e) {
					e.printStackTrace();
					res.setCode(BaseRes.ERRORPARAM_CODE);
					res.setDes("商品id错误！");
					logger.warn("ios内购二次验证：商品id错误 无法截取金额！");
					return res;
				}
				
				String uuid = IdGen.uuid();
				
				IosWithin bsbWithinIos = new IosWithin();
				bsbWithinIos.setUuid(receiptMD5);
				bsbWithinIos.setPrice(money);
				bsbWithinIos.setProductId(uuid);
				bsbWithinIos.setProductType(PayTypeUtil.GOODSTYPE_BALANCE_RECHARGE);
				bsbWithinIos.setPurchaseDate(date);
				bsbWithinIos.setQuantity(quantity);
				bsbWithinIos.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
				bsbWithinIos.setTransactionId(transaction_id);
				bsbWithinIos.setUserId(userId);
				iosWithinMapper.insertSelective(bsbWithinIos);
				PurchaseOrder purchaseOrder = new PurchaseOrder();
				
				//BsbBalanceRech bsbBalanceRech = new BsbBalanceRech();
				purchaseOrder.setUuid(uuid);
				purchaseOrder.setCurrentPrice(money);
				purchaseOrder.setPaymentStatus(PayCommonUtil.PAYSUCCESS_STATUS);
				purchaseOrder.setPayType(PayTypeUtil.PAYTYPE_WITHIN);
				purchaseOrder.setOriginalPrice(money);
				purchaseOrder.setPhoneNum(userId);
				purchaseOrder.setPaymentDate(date);
				purchaseOrderMapper.insertSelective(purchaseOrder);
				logger.info("添加ios内购订单："+JsonUtil.toJson(bsbWithinIos));
				logger.info("添加充值记录："+JsonUtil.toJson(purchaseOrder));
				updateIosWithin(uuid,price,userId);
				res.setCode(BaseRes.SUCCESS_CODE);
				res.setDes(BaseRes.SUCCESS_DES);
				return res;
				
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes(BaseRes.FAIL_DES);
			return res;
		}
		
	}
	
	public Object checkIosWithIn(String receipt,String userId,double money){
		BaseRes<String> res = new BaseRes<String>();
		
		try {
			if (StringUtils.isBlank(receipt)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			String sendHttpsCoon = httpClientService.sendHttpsCoon(certificateUrl, receipt);
			JSONObject str2Obj = JsonUtil.str2Obj(sendHttpsCoon);
			String statuscode = str2Obj.getString("status");
			String iosficteurl=certificateUrl;
			String receipt_r ="";
			logger.info("ios内购二次验证返回参数："+str2Obj);	
			String md5 = Md5Util.Md5(receipt);
			
			boolean withInIos = isWithInIos(md5);
			if (withInIos) {
				res.setCode(BaseRes.SUCCESS_CODE);
				res.setDes("不能重复购买！");
				return res;
			}
			if (statuscode.equals("0")) {
				
				receipt_r = str2Obj.getString("receipt");
				Object checkIosResult = checkIosResult(receipt_r, userId, money, md5);
				return checkIosResult;
				
			}else if (statuscode.equals("21007")||statuscode.equals("21008")) {
				if (statuscode.equals("21007")) {
					iosficteurl=certificateUrlTest;
				}else {
					iosficteurl=certificateUrl;
				}
				String sendHttpsCoontwo = httpClientService.sendHttpsCoon(iosficteurl, receipt);
				JSONObject str2Objtwo = JsonUtil.str2Obj(sendHttpsCoontwo);
				String statuscodetwo = str2Objtwo.getString("status");
				logger.info("ios内购二次验证返回参数："+str2Objtwo);	
				if (statuscodetwo.equals("0")) {
					receipt_r = str2Objtwo.getString("receipt");
					Object checkIosResult = checkIosResult(receipt_r, userId, money, md5);
					return checkIosResult;
						
				}else {
						//失败
					res.setCode(BaseRes.FAIL_CODE);
					res.setDes("验证失败"+statuscode);
					return res;
				}
					
				
			}else {
				//错误
				res.setCode(BaseRes.FAIL_CODE);
				res.setDes("验证失败"+statuscode);
				return res;
			}
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes("验证失败！");
			return res;
		}
		
	}
	
	/**
	 * ios内购流水
	 */
	private void updateIosWithin(String productId,double price,String userId){
		User user = new User();
		user.setPhoneNumber(userId);
		user.setBalance(price);
		logger.info("ios内购充值用户余额增加:"
				+ "增加金额："+price);
		userService.updateUserAvisoryNumAndBalance(user);
		logger.info("ios内购充值用户余额增加流水:");
		userDealRecordService.userdealRecordRunning(userId, productId, PayTypeUtil.PAYTYPE_WITHIN, price, PayTypeUtil.GOODSTYPE_BALANCE_RECHARGE, "ios内购充值", PayTypeUtil.TRDETYPE_INCOME, Const.ACCOUNTPERSON);
		logger.info("ios内购充值 解税宝收入流水:");
		userDealRecordService.userdealRecordRunning(Const.JSBUSERID, productId, PayTypeUtil.PAYTYPE_WITHIN, price, PayTypeUtil.GOODSTYPE_BALANCE_RECHARGE, "ios内购充值", PayTypeUtil.TRDETYPE_INCOME, Const.ACCOUNTPERSON);
		logger.info("ios内购充值 解税宝支出流水:");
		userDealRecordService.userdealRecordRunning(Const.JSBUSERID, productId, PayTypeUtil.PAYTYPE_WITHIN, price, PayTypeUtil.GOODSTYPE_BALANCE_RECHARGE, "ios内购充值", PayTypeUtil.TRDETYPE_EXPENDITURE, Const.ACCOUNTPERSON);

	}
}
